package com.paw.ruoyi.admin.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.paw.ruoyi.admin.common.domain.Result;
import com.paw.ruoyi.admin.common.enums.CommonResponseCodeEnum;
import com.paw.ruoyi.admin.config.AliyunSmsProperty;
import com.paw.ruoyi.admin.dto.SendSmsDto;
import com.paw.ruoyi.admin.service.ISmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Rubble
 * @date 2022/3/10
 **/
@Slf4j
@Service
public class AliDysmsServiceImpl implements ISmsService {


  @Autowired
  private AliyunSmsProperty aliyunSmsProperty;

  private Client client;

  @Override
  public Result<Boolean> sendSms (SendSmsDto requestDto) {

    SendSmsRequest sendSmsRequest = new SendSmsRequest();
    sendSmsRequest.setPhoneNumbers(requestDto.getPhoneNumbers());
    sendSmsRequest.setTemplateCode(requestDto.getTemplateCode());
    sendSmsRequest.setSignName(aliyunSmsProperty.getSignName());
    sendSmsRequest.setTemplateParam(requestDto.getTemplateParam());
    // 复制代码运行请自行打印 API 的返回值
    Result<Boolean> result = null;
    try {
      SendSmsResponse sendSmsResponse = getClient().sendSms(sendSmsRequest);
      //{"body":{"bizId":"120617046917858271^0","code":"OK","message":"OK","requestId":"7EF57375-02BF-5482-A081-5EC35BAA8CC5"},"headers":{"access-control-allow-origin":"*","date":"Thu, 10 Mar 2022 13:10:58 GMT","content-length":"110","access-control-max-age":"172800","x-acs-request-id":"7EF57375-02BF-5482-A081-5EC35BAA8CC5","access-control-allow-headers":"X-Requested-With, X-Sequence, _aop_secret, _aop_signature, x-acs-action, x-acs-version, x-acs-date, Content-Type","connection":"keep-alive","content-type":"application/json;charset=utf-8","access-control-allow-methods":"POST, GET, OPTIONS, PUT, DELETE","x-acs-trace-id":"1aaaca7ff4620bae244c7a36001af568"}}

      String code = sendSmsResponse.getBody().getCode();
      String message = sendSmsResponse.getBody().getMessage();
      boolean success = "OK".equals(code);
      result = Result.result(success);
      result.setMessage(message);
    } catch (Exception e) {
      result = Result.result(CommonResponseCodeEnum.ERROR);
      log.error("send sms ex. {} ",e.getMessage(),e);
    }

    return result;
  }

  private Client getClient () throws Exception {
    if(client==null){
      Config config = new Config()
          // 您的AccessKey ID
          .setAccessKeyId(aliyunSmsProperty.getAccessKeyId())
          // 您的AccessKey Secret
          .setAccessKeySecret(aliyunSmsProperty.getAccessKeySecret());
      // 访问的域名
      config.endpoint = "dysmsapi.aliyuncs.com";
      client = new Client(config);
    }
    return client;
  }
}
